package com.veo.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.veo.entity.User;
import com.veo.service.UserService;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component("readerUpdateAction")
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
@Results({
        @Result(name = "success",params = {"root","resultMap"},type = "json"),
})
public class ReaderUpdateAction extends ActionSupport implements ModelDriven<User> {

    private User user=new User();
    @Autowired
    private UserService userService;
    private Map<String,String> resultMap;

    public Map<String, String> getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map<String, String> resultMap) {
        this.resultMap = resultMap;
    }

    @Override
    public User getModel() {
        return user;
    }

    @Action("updateInfo")
    public String updateInfo(){
        int i = userService.updateUserInfo(user);
        System.out.println(user);
        resultMap=new HashMap<String,String>();
        if (i>0){
            resultMap.put("msg","ok");
            return "success";
        }
        resultMap.put("msg","error");
        return "success";
    }

    @Action("updateUserPass")
    public String updatePass(){
        resultMap=new HashMap<String,String>();
        User oldUser = userService.findLoginUser(user);
        System.out.println(oldUser);
        if (oldUser!=null){
            String newPass = ServletActionContext.getRequest().getParameter("newPass");
            System.out.println(newPass);
            user.setPassword(newPass);
            user.setStatus(oldUser.getStatus());
            System.out.println("newUser"+user);
            int i = userService.updateUserInfo(user);
            if (i>0){
                resultMap.put("msg","ok");
            }
        }else {
            resultMap.put("msg","PassError");
        }
        return "success";
    }
}
